import sys
import os
import bcrypt
from flask import Blueprint, request, jsonify
from flask_jwt_extended import create_access_token, jwt_required, get_jwt_identity
from backend.db.db_helpers import query_db, execute_db

auth_bp = Blueprint('auth', __name__)

@auth_bp.route('/register', methods=['POST'])
def register():
    """用户注册"""
    try:
        data = request.get_json()
        
        # 检查必填字段
        if not data.get('username') or not data.get('password') or not data.get('role'):
            return jsonify({'error': '缺少必填字段: username, password 或 role'}), 400
        
        # 检查角色是否有效
        if data['role'] not in ['student', 'teacher']:
            return jsonify({'error': '无效的角色，必须是 student 或 teacher'}), 400
        
        # 检查用户名是否已存在
        existing_user = query_db('SELECT * FROM users WHERE username = ?', [data['username']], one=True)
        if existing_user:
            return jsonify({'error': '用户名已存在'}), 409
        
        # 密码加密
        hashed_password = bcrypt.hashpw(data['password'].encode('utf-8'), bcrypt.gensalt())
        
        # 创建用户
        user_id = execute_db('''
            INSERT INTO users (username, password, role)
            VALUES (?, ?, ?)
        ''', [data['username'], hashed_password, data['role']])
        
        return jsonify({'message': '用户注册成功', 'user_id': user_id}), 201
        
    except Exception as e:
        return jsonify({'error': f'注册失败: {str(e)}'}), 500

@auth_bp.route('/login', methods=['POST'])
def login():
    """用户登录"""
    try:
        data = request.get_json()
        
        # 检查必填字段
        if not data.get('username') or not data.get('password'):
            return jsonify({'error': '缺少必填字段: username 或 password'}), 400
        
        # 查找用户
        user = query_db('SELECT * FROM users WHERE username = ?', [data['username']], one=True)
        if not user:
            return jsonify({'error': '用户不存在'}), 404
        
        # 验证密码
        if not bcrypt.checkpw(data['password'].encode('utf-8'), user['password']):
            return jsonify({'error': '密码错误'}), 401
        
        # 生成访问令牌
        access_token = create_access_token(identity=user['id'])
        
        return jsonify({
            'access_token': access_token,
            'user': {
                'id': user['id'],
                'username': user['username'],
                'role': user['role']
            }
        }), 200
        
    except Exception as e:
        return jsonify({'error': f'登录失败: {str(e)}'}), 500

@auth_bp.route('/profile', methods=['GET'])
@jwt_required()
def get_profile():
    """获取用户信息"""
    try:
        user_id = get_jwt_identity()
        user = query_db('SELECT id, username, role FROM users WHERE id = ?', [user_id], one=True)
        
        if not user:
            return jsonify({'error': '用户不存在'}), 404
        
        return jsonify({'user': user}), 200
        
    except Exception as e:
        return jsonify({'error': f'获取用户信息失败: {str(e)}'}), 500